package us.versus.them.archetype;

import neko.io.File;
import neko.FileSystem;

class Util {
	public static var COMMAND_KEY  = "${COMMAND}";
	public static var PWD_KEY = "${PWD}";

	public static function parseArgs( args:Array<String> ) : Hash< String > {
		var values:Hash< String > = new Hash< String >();
		values.set( COMMAND_KEY, "" );
		for( arg in args ) {
			if ( '-' == arg.charAt( 0 ) ) {
				var key = arg.substr( 1 );
				var val = "";
				var eqx = key.indexOf( '=' );
				if ( -1 != eqx ) {
					val = key.substr( eqx + 1 );
					key = key.substr( 0, eqx );
				}
				values.set( key, val );
			} else {
				if ( "" == values.get( COMMAND_KEY ) ) {
					values.set( COMMAND_KEY, arg );
				} else {
					values.set( PWD_KEY, arg );
				}
			}
		}
		return values;
	}

	public static function firstUp( string:String ) : String {
		return (
			string.substr( 0, 1 ).toUpperCase()
			+ string.substr( 1 )
		);
	}

	public static function mkdir( path:String ) {
		var created = true;
		var pwd = "";

		var d = if( isWindozePath( path ) ) {
			"\\";
		} else {
			"/";
		}

		for ( dir in path.split( d ) ) {
			if ( "" == pwd ) {
				/*
				   this special case code brought to you by
				   the morons in redmond
				*/
				if ( isWindozePath( path ) ) {
					pwd += dir;
				} else {
					pwd += d + dir;
				}
			} else {
				pwd += d + dir;
			}
			if ( FileSystem.exists( pwd ) ) {
				if ( !FileSystem.isDirectory( pwd ) ) {
					throw( pwd + ' is not a directory!!!' );
				}
			} else {
				try {
					FileSystem.createDirectory( pwd );
				} catch( e:Dynamic ) {
					created = false;
				}
			}
		}
		return created;
	}

	public static function isWindozePath( path:String ) {
		return ~/\\/.match( path ); // this is a really lame test...
	}

	public static function dozer( path:String ) {
		return if ( isWindozePath( path ) ) {
			~/\//g.replace( path, '\\' );
		} else {
			path;
		}
	}
}
